package com.beiing.tianshuai.tianshuai.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

import java.util.regex.Pattern;

/**
 * 得到指定汉字的拼音
 * Created by magikliu on 2017/7/24.
 */

public class PinYinUtils {

    /**
     * 获取字符串首字母
     *
     * @param s 汉字或字母
     * @return 拼音
     */
    public static String getPinyin(String s) {
        String result = null;
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //只能对单个汉字转换
        char[] arr = s.toCharArray();
        for (char anArr : arr) {
            if (Character.isWhitespace(anArr)) {
                continue;
            }
            try {
                String[] pinyinArr = PinyinHelper.toHanyuPinyinStringArray(anArr, format);
                if (pinyinArr != null) {
                    result = pinyinArr[0].toUpperCase();
                } else {
                    result = String.valueOf(arr[0]).toUpperCase();
                }
            } catch (Exception e) {
                //不是正确的汉字
                if (Pattern.matches("[a-z]|[A-Z]+", String.valueOf(anArr))) {
                    result = String.valueOf(anArr).toUpperCase();
                } else {
                    result = "#";
                }
            }
            break;
        }
        return result;
    }
}